<!--
 * @Descripttion:  
 * @version:  
 * @Author: chenxf
 * @Date: 2023-03-02 11:10:08
-->
<template>
  <a-modal
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :bodyStyle="bodyStyle"
    style="top: 0px;"
    destroyOnClose
    :footer="null"
    cancelText="关闭"
    v-if="visible"
  >
    <div class="content-wrapper">
      <div class="content-main">
        <template v-if="!nodeLoading">
          <div class="deployment-node-wrapper">
            <div class="deployment-node-title">流程节点:</div>
            <div
              v-for="item in deploymentNodeLists"
              class="deployment-node"
              :class="{ select: selectDeploymentNode.id == item.id }"
              @click="changeDeploymentNode(item)"
            >
              {{ item.processNodeName }}
            </div>
          </div>
          <template v-if="!formLoading">
            <div class="assignee-configs-form">
              <div class="table-tool">
                <a-button @click="handleCopyNode" v-if="isEdit">拷贝节点</a-button>
                <a-button @click="deleteNode" type="danger" v-if="isEdit">清空配置</a-button>
              </div>

              <div>
                <a-form-model
                  ref="ruleForm"
                  :model="assigneesForm"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                >
                  <template v-for="(config, index) in form.processConditionConfig">
                    <a-row class="table-tr">
                      <a-col span="24">
                        <a-form-model-item
                          :label="config.name"
                          :prop="config.column"
                          :rules="{
                            required: config.require,
                            message: '值不能为空',
                            trigger: 'blur'
                          }"
                        >
                          <template v-if="config.tag && config.tag.tagName">
                            <component
                              :is="config.tag.tagName"
                              v-bind="config.tag.tagParam"
                              v-model="assigneesForm[config.column]"
                            ></component>
                          </template>
                          <template v-else>
                            <a-input v-model="assigneesForm[config.column]" />
                          </template>
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                  </template>
                  <a-row>
                    <a-form-model-item
                      label="人员类型"
                      prop="assigneeType"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                    >
                      <a-select v-model="assigneesForm.assigneeType" @change="changeAssigneeType">
                        <a-select-option :value="item.value" v-for="item in assigneeTypeOptions" :key="item.value">
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                    <a-form-model-item
                      label="指定"
                      prop="assignee"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                      v-if="assigneesForm.assigneeType == 'ASSIGN'"
                    >
                      <UserSelect v-model="assigneesForm.assignee" />
                    </a-form-model-item>
                    <a-form-model-item
                      label="指定"
                      prop="assignee"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                      v-if="assigneesForm.assigneeType == 'ROLE'"
                    >
                      <RoleSelect v-model="assigneesForm.assignee" />
                    </a-form-model-item>
                    <a-form-model-item
                      label="指定"
                      prop="assignee"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                      v-if="assigneesForm.assigneeType == 'DEPT'"
                    >
                      <DeptSelect v-model="assigneesForm.assignee" />
                    </a-form-model-item>
                    <a-form-model-item
                      label="指定"
                      prop="assignee"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                      v-if="assigneesForm.assigneeType == 'PROCESS_VARIABLE_ASSIGN_ROLE'"
                    >
                      <a-input v-model="assigneesForm.assignee"></a-input>
                    </a-form-model-item>
                    <a-form-model-item
                      label="指定"
                      prop="assignee"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                      v-if="assigneesForm.assigneeType == 'PROCESS_VARIABLE_ASSIGN_DEPT'"
                    >
                      <a-input v-model="assigneesForm.assignee"></a-input>
                    </a-form-model-item>
                    <a-form-model-item
                      label="指定"
                      prop="assignee"
                      :rules="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur'
                      }"
                      v-if="assigneesForm.assigneeType == 'PROCESS_VARIABLE_ASSIGN'"
                    >
                      <a-input v-model="assigneesForm.assignee"></a-input>
                    </a-form-model-item>
                  </a-row>
                </a-form-model>
              </div>
            </div>
            <div class="form-footer">
              <a-button type="primary" @click="submitEvent" :loading="isLoading">保存</a-button>
            </div>
          </template>
          <a-spin v-else class="spin-wrapper">
            <a-icon slot="indicator" type="loading" style="font-size: 30px" spin />
          </a-spin>
        </template>
        <a-spin v-else class="spin-wrapper">
          <a-icon slot="indicator" type="loading" style="font-size: 40px" spin />
        </a-spin>
      </div>
    </div>
    <a-modal v-model="visibleVersion" :title="'版本(' + copyVersion.version + ')拷贝至'" on-ok="handleOk">
      <template slot="footer">
        <a-button key="back" @click="cancelVisible">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="saveCopyVersion">
          拷贝
        </a-button>
      </template>
      <a-radio-group v-model="copyVersionId">
        <a-radio
          :value="item.deploymentId"
          v-for="item in versionLists"
          :disabled="copyVersion.deploymentId == item.deploymentId"
          :key="item.deploymentId"
        >
          版本 {{ item.version }}
        </a-radio>
      </a-radio-group>
      <br />
      <a-checkbox v-model="duplicateAllAssignee">
        是否拷贝到所有流程人员配置
      </a-checkbox>
    </a-modal>
    <a-modal v-model="visibleNode" :title="'节点(' + copyNode.processNodeName + ')拷贝至'" on-ok="handleOk">
      <template slot="footer">
        <a-button key="back" @click="cancelVisibleNode">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="saveCopyNode">
          拷贝
        </a-button>
      </template>
      <a-checkbox-group v-model="copyNodeId">
        <a-checkbox
          :value="item.processNodeCode"
          v-for="item in deploymentNodeLists"
          :disabled="copyNode.processNodeCode == item.processNodeCode"
          :key="item.processNodeCode"
        >
          节点- {{ item.processNodeName }}
        </a-checkbox>
      </a-checkbox-group>
    </a-modal>
    <!-- </a-spin> -->
  </a-modal>
</template>

<script>
import { httpAction, getAction, postAction, putAction, deleteAction } from '@/api/manage'
import UserSelect from '@/views/common/userSelect/index.vue'
import RoleSelect from '@/views/common/roleSelect/index.vue'
import DeptSelect from '@/views/common/deptSelect/index.vue'
import JetpieceDictSelectTag from '@/components/jetpiece/JetpieceDictSelectTag.vue'
export default {
  name: 'ExtActProcessAssigneeModal',
  components: { UserSelect, RoleSelect, DeptSelect, JetpieceDictSelectTag },
  props: {
    visible: Boolean,
    info: Object,
    deploymentId: [String, Number],
    configId: [String, Number]
  },
  data() {
    return {
      title: '流程人员',
      modalWidth: 1200,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      bodyStyle: {
        padding: '0',
        height: window.innerHeight - 80 + 'px'
      },
      confirmLoading: false,
      processKey: '',
      nodeList: '/act/process/extActProcessNodeDeployment/list',
      historyList: '/act/process/extActProcess/processDeploymentList',
      versionLists: [],
      selectVersion: {},
      extActProcessNode: '/act/process/extActProcessNode/list',
      deploymentNodeLists: [],
      selectDeploymentNode: {},
      form: {
        processConditionConfig: []
      },
      extActProcessAssigneesInfo: {}, //流程人员信息
      assigneesForm: {
        assignee: undefined
      },
      isEdit: false,
      rules: {},
      visibleVersion: false,
      copyVersionId: undefined,
      copyVersion: {},
      assigneeTypeOptions: [
        { value: 'ROLE', label: '角色' },
        { value: 'DEPT', label: '部门' },
        { value: 'ASSIGN', label: '用户' },
        { value: 'PROCESS_VARIABLE_ASSIGN_ROLE', label: '从流程选取角色' },
        { value: 'PROCESS_VARIABLE_ASSIGN_DEPT', label: '从流程选取部门' },
        { value: 'PROCESS_VARIABLE_ASSIGN', label: '从流程选取用户' }
      ],
      nodeLoading: false,
      versionLoading: false,
      isLoading: false,
      formLoading: false,
      visibleNode: false,
      copyNode: {},
      copyNodeId: [],
      duplicateAllAssigneeNode: false,
      duplicateAllAssignee: true,
      api: {
        list: '/act/processConditionConfigNodes'
      }
    }
  },
  mounted() {
    this.getNodeHistory()
  },
  methods: {
    close() {
      this.$emit('close')
      this.$emit('update:visible', false)
    },
    handleOk() {
      const that = this
      that.$emit('ok')
    },
    handleCancel() {
      this.close()
    },
    //获取版本信息
    getHistory() {
      this.versionLoading = true
      this.nodeLoading = true
      getAction(this.historyList, { processKey: this.info.processKey }).then(res => {
        if (res.success) {
          this.versionLists = res.result.rows
          this.selectVersion = this.versionLists[0]
          if (this.versionLists.length) {
            this.deploymentId = this.versionLists[0].deploymentId
            this.getNodeHistory()
          } else {
            this.nodeLoading = false
          }
        } else {
          this.$message.warning(res.message)
          this.versionLists = []
          this.nodeLoading = false
        }
        this.versionLoading = false
      })
    },
    //获取节点信息
    getNodeHistory() {
      this.nodeLoading = true
      getAction(this.nodeList, { deploymentId: this.deploymentId }).then(res => {
        if (res.success) {
          this.deploymentNodeLists = res.result.rows
          this.selectDeploymentNode = this.deploymentNodeLists[0]
          this.getConfig()
        } else {
          this.$message.warning(res.message)
          this.deploymentNodeLists = []
        }
        this.nodeLoading = false
      })
    },
    //获取人员配置条件
    getConfig() {
      const postData = {
        actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
        deploymentId: this.deploymentId,
        actProcessId: this.info.id,
        pageSize: 500
      }
      this.formLoading = true
      getAction('/act/processConditions', postData).then(res => {
        if (res.result.rows.length) {
          this.form = res.result.rows[0]
          this.assigneesForm = {}
          this.form.processConditionConfig.forEach(i => {
            // let tagParam = {}
            // try {
            //   let json = i.tag
            //   tagName = json.tagName
            //   tagParam = json.tagParam
            // } catch (e) {}
            // i.tag.tagParam = tagParam
            this.$set(this.assigneesForm, i.column, undefined)
            this.assigneesForm[i.column] = undefined
          })
          this.getConfigValue()
        } else {
          this.form = {
            actEventType: 'TASK_CREATED',
            assigneeConditionConfig: '',
            assigneeTypeConfig: '',
            notifyAssignee: '',
            processConditionConfig: []
          }
          this.assigneesForm = {}
          this.getConfigValue()
        }
        this.formLoading = false
      })
    },
    //获取流程人员
    getConfigValue() {
      const postData = {
        actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
        deploymentId: this.deploymentId,
        actProcessId: this.info.id,
        configId: this.configId,
        pageSize: 500
      }
      getAction(this.api.list, postData).then(res => {
        if (res.result.rows.length) {
          this.extActProcessAssigneesInfo = res.result.rows[0]
          this.isEdit = true
          for (let i in this.extActProcessAssigneesInfo.processCondition) {
            this.$set(this.assigneesForm, i, this.extActProcessAssigneesInfo.processCondition[i])
          }
          this.$set(this.assigneesForm, 'assigneeType', this.extActProcessAssigneesInfo.assigneeType)
          this.$set(this.assigneesForm, 'assignee', this.extActProcessAssigneesInfo.assignee)
        } else {
          this.isEdit = false
        }
      })
    },
    //切换版本
    changeVersion(row) {
      this.selectVersion = row
      this.getNodeHistory()
    },
    //切换节点
    changeDeploymentNode(row) {
      this.selectDeploymentNode = row
      this.getConfig()
    },
    //提交
    submitEvent() {
      this.$refs.ruleForm.validate((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        } else {
          this.saveNodeConfig()
        }
      })
    },
    saveNodeConfig() {
      if (!this.isEdit) {
        let processCondition = {}
        this.form.processConditionConfig.forEach(i => {
          processCondition[i.column] = this.assigneesForm[i.column]
        })
        const postData = {
          actEventType: 'TASK_CREATED',
          actProcessId: this.info.id,
          actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
          deploymentId: this.selectVersion.deploymentId,
          processCondition,
          assignee: this.assigneesForm.assignee,
          assigneeType: this.assigneesForm.assigneeType,
          notifyAssignee: true,
          configId: this.configId
        }
        this.isLoading = true
        postAction(this.api.list, postData).then(res => {
          if (res.success) {
            this.$message.success('保存成功')
            this.getConfig()
          } else {
            this.$message.error(res.message)
          }
          this.isLoading = false
        })
      } else {
        let processCondition = {}
        this.form.processConditionConfig.forEach(i => {
          processCondition[i.column] = this.assigneesForm[i.column]
        })
        const postData = {
          actEventType: 'TASK_CREATED',
          actProcessId: this.info.id,
          actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
          deploymentId: this.selectVersion.deploymentId,
          processCondition,
          assignee: this.assigneesForm.assignee,
          assigneeType: this.assigneesForm.assigneeType,
          id: this.extActProcessAssigneesInfo.id,
          notifyAssignee: true,
          configId: this.configId
        }
        this.isLoading = true
        putAction(this.api.list, postData).then(res => {
          if (res.success) {
            this.$message.success('保存成功')
          } else {
            this.$message.error(res.message)
          }
          this.isLoading = false
        })
      }
    },
    removeConfig(item) {
      let index = this.form.processConditionConfig.indexOf(item)
      if (index !== -1) {
        let _this = this
        this.$confirm({
          title: '',
          content: '确定删除该行?',
          onOk() {
            _this.form.processConditionConfig.splice(index, 1)
          },
          onCancel() {}
        })
      }
    },
    deleteNode() {
      let id = this.extActProcessAssigneesInfo.id
      if (!id) {
        this.$message.error('未有id')
        return
      }
      let _this = this
      this.$confirm({
        title: '确定清空流程人员',
        content: '确定清空流程人员?',
        onOk() {
          deleteAction(_this.api.list + '/' + id).then(res => {
            if (res.success) {
              _this.$message.success('删除成功')
              _this.getConfig()
            } else {
              _this.$message.error(res.message)
            }
          })
        },
        onCancel() {}
      })
    },
    saveCopyVersion() {
      const postData = {
        actProcessId: this.info.id,
        targetDeploymentId: this.copyVersion.deploymentId,
        deploymentId: this.copyVersionId,
        duplicateAllAssignee: this.duplicateAllAssignee
      }
      putAction(this.api.list + '/duplicate', postData).then(res => {
        if (res.success) {
          this.$message.success('拷贝成功')
          this.visibleVersion = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    cancelVisible() {
      this.visibleVersion = false
    },
    handleCopyVersion(row) {
      const postData = {
        actProcessId: this.info.id,
        deploymentId: row.deploymentId,
        pageSize: 500
      }
      getAction('/act/extActProcessAssigneeConfigs', postData).then(res => {
        if (res.result.rows.length) {
          this.visibleVersion = true
          this.copyVersion = row
        } else {
          this.$message.error('该流程无人员配置,无法拷贝')
        }
      })
    },
    changeAssigneeType() {
      this.$set(this.assigneesForm, 'assignee', '')
    },
    handleCopyNode() {
      this.copyNode = this.selectDeploymentNode
      this.copyNodeId = []
      this.visibleNode = true
    },
    cancelVisibleNode() {
      this.visibleNode = false
    },
    saveCopyNode() {
      // const postData = {
      //   actProcessId: this.info.id,
      //   targetDeploymentId: this.copyNode.deploymentId,
      //   deploymentId: this.copyNode.deploymentId,
      //   duplicateAllAssignee: this.duplicateAllAssigneeNode,
      // }
      if (this.copyNodeId.length == 0) {
        this.$message.error('未选择')
        return
      }
      putAction(this.api.list + '/' + this.extActProcessAssigneesInfo.id + '/duplicate/' + this.copyNodeId.join()).then(
        res => {
          if (res.success) {
            this.$message.success('拷贝成功')
            this.visibleNode = false
          } else {
            this.$message.error(res.message)
          }
        }
      )
    }
  }
}
</script>

<style lang="less" scoped>
.ant-modal-header {
  //padding: 0 !important;
}
// 兼容1.6.2版本的antdv全屏
/deep/ .ant-modal {
  top: 0;
  padding: 0;
}
.content-wrapper {
  display: flex;
  height: 100%;
  padding: 20px;
  .content-left {
    width: 240px;
    height: 100%;
    border-right: 1px solid #999;
    padding-right: 20px;
  }
  .content-main {
    width: calc(100% - 240px);
    height: 100%;
    padding: 20px;
    .form-footer {
      text-align: center;
    }
  }
  .spin-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .version-list {
    color: #000;
    font-size: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 40px;
    flex-wrap: wrap;
    padding: 4px;
    border-radius: 8px;
    gap: 6px;
    margin-bottom: 4px;
    cursor: pointer;
    &.select {
      background: #f1f2f4;
    }
    /deep/.ant-tag {
      scale: 0.88;
      margin-right: 2px;
    }
    .version-tag {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 21px;
      margin-left: 4px;
      font-weight: 500;
      color: #24b35f;
      background-color: #edfcf0;
      border: 1px solid #8ad7a7;
      border-radius: 4px;
      > span {
        scale: 0.85;
        font-size: 12px;
      }
    }
  }
  .process-name {
    height: 60px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    color: #33383e;

    span {
      position: relative;
      display: inline-flex;
    }
    // > ::after {
    //   border-bottom: 1px solid #33383e;
    //   width: 100%;
    //   height: 1px;
    //   content: '';
    //   display: inline-block;
    //   position: absolute;
    //   bottom: -4px;
    // }
  }
  .deployment-node {
    display: inline-flex;
    color: #7f8792;
    margin-right: 14px;
    cursor: pointer;
    &.select {
      color: #000;
      border-bottom: 1px solid;
    }
  }
  .deployment-node-wrapper {
    display: flex;
    .deployment-node-title {
      display: inline-flex;
      padding-right: 20px;
    }
  }
  .assignee-configs-form {
    padding: 20px 0;
    .table-tool {
      padding-bottom: 10px;
      > button {
        margin-right: 10px;
      }
    }
    .assignee-configs-form-tip {
      padding-top: 20px;
    }
  }
  .assignee-configs-form-inner {
    border: 1px solid #f1f2f4;
    .table-header {
      // padding: 20px;
      > .ant-col {
        padding: 20px 0;
        border-right: 1px solid #f1f2f4;
        padding-left: 10px;
      }
    }
    .table-tr {
      border-top: 1px solid #f1f2f4;
      > .ant-col {
        border-right: 1px solid #f1f2f4;
        padding-left: 10px;
      }
      .form-delete {
        position: absolute;
        right: 8px;
        top: 4px;
        font-size: 20px;
        cursor: pointer;
      }
    }
    // padding: 20px 0;
  }
}
</style>
